const cloud = require("wx-server-sdk");
const dayjs = require('dayjs')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;

// 获取openid
const getOpenId = async () => {
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: cloud.getWXContext().APPID,
    unionid: wxContext.UNIONID
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建产品和订单相关的集合
    await db.createCollection("products");
    await db.createCollection("orders");
    await db.createCollection("users");
    await db.createCollection("coupons");
    await db.createCollection("banners");
    await db.createCollection("shareRecords");
    await db.createCollection("inviteRecords");

    // 初始化一些基础数据
    await initializeBaseData();

    return {
      success: true,
      message: "数据库集合创建成功"
    };
  } catch (e) {
    console.log('集合创建错误:', e);
    return {
      success: true,
      message: "集合已存在或创建成功"
    };
  }
};

// 初始化基础数据
const initializeBaseData = async () => {
  const db = cloud.database();

  // 如果products集合为空，添加示例商品
  const productCount = await db.collection('products').count();
  if (productCount.total === 0) {
    const sampleProducts = [
      {
        name: "高品质智能蓝牙耳机",
        description: "智能降噪技术，超长续航，舒适佩戴体验",
        images: ["https://example.com/headphone1.jpg", "https://example.com/headphone2.jpg"],
        originalPrice: 59900, // 分
        groupPrice: 29900,
        groupCount: 10,
        type: "traditional",
        stock: 100,
        category: "数码电器",
        status: 1,
        tag: "限时特惠",
        sort: 100,
        startTime: new Date(),
        endTime: new Date(Date.now() + 72 * 60 * 60 * 1000), // 72小时后
        createTime: new Date(),
        updateTime: new Date(),
        sales: 0,
        rating: 4.8,
        reviewCount: 128
      },
      {
        name: "网红零食大礼包",
        description: "精选各地美味零食，让你一次尝个够",
        images: ["https://example.com/snacks1.jpg"],
        originalPrice: 19900,
        groupPrice: 9900,
        groupCount: 8,
        type: "traditional",
        stock: 200,
        category: "美食特产",
        status: 1,
        tag: "新品尝鲜",
        sort: 90,
        startTime: new Date(),
        endTime: new Date(Date.now() + 48 * 60 * 60 * 1000),
        createTime: new Date(),
        updateTime: new Date(),
        sales: 0,
        rating: 4.5,
        reviewCount: 86
      },
      {
        name: "抽奖团 - iPhone 15 Pro",
        description: "参与抽奖，有机会以超值价格获得最新iPhone",
        images: ["https://example.com/iphone15.jpg"],
        originalPrice: 899900,
        groupPrice: 179980, // 20% 定金
        groupCount: 50,
        type: "lottery",
        stock: 5,
        category: "数码电器",
        status: 1,
        tag: "抽奖团购",
        sort: 80,
        startTime: new Date(),
        endTime: new Date(Date.now() + 72 * 60 * 60 * 1000),
        createTime: new Date(),
        updateTime: new Date(),
        winnerCount: 2, // 中奖人数
        consolationCoupon: 1000, // 10元安慰券
        sales: 0,
        rating: 5.0,
        reviewCount: 0
      }
    ];

    for (const product of sampleProducts) {
      await db.collection('products').add({ data: product });
    }
  }

  // 初始化banner数据
  const bannerCount = await db.collection('banners').count();
  if (bannerCount.total === 0) {
    const sampleBanners = [
      {
        image: "https://example.com/banner1.jpg",
        url: "/pages/activity/new-user",
        title: "新用户专享",
        sort: 100,
        status: 1,
        startTime: new Date(),
        endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        createTime: new Date()
      },
      {
        image: "https://example.com/banner2.jpg",
        url: "/pages/activity/hot-sale",
        title: "热销商品",
        sort: 90,
        status: 1,
        startTime: new Date(),
        endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        createTime: new Date()
      }
    ];

    for (const banner of sampleBanners) {
      await db.collection('banners').add({ data: banner });
    }
  }
};

// 查询数据
const selectRecord = async () => {
  return await db.collection("sales").get();
};

// 更新数据
const updateRecord = async (event) => {
  try {
    for (let i = 0; i < event.data.length; i++) {
      await db
        .collection("sales")
        .where({
          _id: event.data[i]._id,
        })
        .update({
          data: {
            sales: event.data[i].sales,
          },
        });
    }
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    await db.collection("sales").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        sales: Number(insertRecord.sales),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("sales")
      .where({
        _id: event.data._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 发放优惠券
const grantCoupon = async (event) => {
  const { openid, couponType } = event

  try {
    const db = cloud.database()

    // 检查用户是否存在
    const userRes = await db.collection('users').where({ openid }).get()
    if (userRes.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = userRes.data[0]
    let couponData = {}

    // 根据优惠券类型创建数据
    if (couponType === 'newUser') {
      // 检查是否已经领取过新人优惠券
      const existCoupon = await db.collection('coupons').where({
        userId: openid,
        type: 'newUser'
      }).get()

      if (existCoupon.data.length > 0) {
        return {
          success: false,
          message: '您已经领取过新人优惠券了'
        }
      }

      couponData = {
        type: 'newUser',
        title: '新用户专享大礼包',
        amount: 2500, // 25元
        minAmount: 5000,
        userId: openid,
        status: 0,
        startTime: new Date(),
        endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
        createTime: new Date(),
        description: '新人专享，满50元减25元',
        categoryLimit: '',
        productLimit: ''
      }
    }

    // 创建优惠券
    await db.collection('coupons').add({ data: couponData })

    // 更新用户记录的优惠券数量
    await db.collection('users').doc(user._id).update({
      data: {
        couponCount: (user.couponCount || 0) + 1,
        updateTime: new Date()
      }
    })

    return {
      success: true,
      message: '优惠券领取成功'
    }

  } catch (error) {
    console.error('发放优惠券失败:', error)
    return {
      success: false,
      message: '优惠券领取失败，请重试'
    }
  }
}

// 创建团购订单
const createGroupOrder = async (event) => {
  const { productId, userId, groupType, amount, quantity, specs } = event

  try {
    const db = cloud.database()

    // 获取商品信息
    const productRes = await db.collection('products').doc(productId).get()
    const product = productRes.data

    if (!product || product.stock < quantity) {
      return {
        success: false,
        message: '商品库存不足'
      }
    }

    // 检查用户是否已参加过该商品的团购
    const existOrder = await db.collection('orders').where({
      productId: productId,
      userId: userId,
      status: _.in(['pending', 'paid'])
    }).get()

    if (existOrder.data.length > 0) {
      return {
        success: false,
        message: '您已经参与过这个团购了'
      }
    }

    // 生成订单号
    const orderNo = 'GP' + Date.now()

    // 创建订单
    const orderData = {
      orderNo,
      productId: productId,
      userId: userId,
      groupType: groupType,
      amount: amount,
      quantity: quantity,
      specs: specs ? JSON.parse(specs) : {},
      status: 'pending', // pending-待支付, paid-已支付, cancelled-已取消
      createTime: new Date(),
      updateTime: new Date(),
      payTime: null,
      groupStatus: 'active', // active-进行中, success-已成团, failed-已失败
      currentCount: 1,
      targetCount: product.groupCount,
      endTime: product.endTime,
      lotteryStatus: groupType === 'lottery' ? 'waiting' : null, // waiting-等待开奖, running-抽奖中, win-中奖, lose-未中奖
      lotteryTime: null,
      winnerCount: groupType === 'lottery' ? product.winnerCount : null,
      consolationCoupon: groupType === 'lottery' ? product.consolationCoupon : null
    }

    const orderRes = await db.collection('orders').add({ data: orderData })

    // 扣减库存
    await db.collection('products').doc(productId).update({
      data: {
        stock: product.stock - quantity,
        sales: (product.sales || 0) + 1,
        updateTime: new Date()
      }
    })

    return {
      success: true,
      data: {
        orderId: orderRes._id,
        orderNo: orderNo,
        amount: amount
      },
      message: '订单创建成功'
    }

  } catch (error) {
    console.error('创建订单失败:', error)
    return {
      success: false,
      message: '订单创建失败，请重试'
    }
  }
}

// 处理团购成团逻辑
const handleGroupSuccess = async (event) => {
  const { orderId } = event

  try {
    const db = cloud.database()

    // 获取订单信息
    const orderRes = await db.collection('orders').doc(orderId).get()
    const order = orderRes.data

    // 判断是否已达到成团条件
    const countRes = await db.collection('orders').where({
      productId: order.productId,
      groupType: order.groupType,
      groupStatus: 'active'
    }).count()

    const completedCount = countRes.total

    // 判断是否成团
    if (completedCount >= order.targetCount) {
      // 更新该商品的所有进行中订单状态
      await db.collection('orders').where({
        productId: order.productId,
        groupType: order.groupType,
        groupStatus: 'active'
      }).update({
        data: {
          groupStatus: 'success',
          updateTime: new Date()
        }
      })

      return {
        success: true,
        message: '团购已成团',
        data: { success: true }
      }
    } else {
      return {
        success: true,
        message: '团购进行中',
        data: { success: false, progress: completedCount / order.targetCount }
      }
    }

  } catch (error) {
    console.error('处理成团逻辑失败:', error)
    return {
      success: false,
      message: '处理成团逻辑失败'
    }
  }
}

// 执行抽奖逻辑
const conductLottery = async (event) => {
  const { groupId } = event

  try {
    const db = cloud.database()

    // 获取该团购的所有参与者
    const participantsRes = await db.collection('orders').where({
      productId: groupId,
      groupType: 'lottery',
      status: 'paid'
    }).get()

    if (participantsRes.data.length === 0) {
      return {
        success: false,
        message: '暂无参与者'
      }
    }

    // 获取商品信息
    const productRes = await db.collection('products').doc(groupId).get()
    const product = productRes.data

    const participants = participantsRes.data
    const totalParticipants = participants.length
    const winnerCount = product.winnerCount || Math.ceil(totalParticipants / 10) // 默认10%中奖率

    // Fisher-Yates 洗牌算法进行抽奖
    const winners = drawLotteryWinners(participants, winnerCount)

    // 处理中奖和未中奖用户
    await processLotteryResults(participants, winners, product)

    return {
      success: true,
      data: {
        winners: winners.length,
        totalParticipants: totalParticipants
      },
      message: '抽奖执行成功'
    }

  } catch (error) {
    console.error('执行抽奖失败:', error)
    return {
      success: false,
      message: '执行抽奖失败'
    }
  }
}

// Fisher-Yates 洗牌算法
function drawLotteryWinners(participants, winnerCount) {
  // 创建参与者副本
  const pool = [...participants]

  // 生成随机种子
  const seed = Date.now() + Math.floor(Math.random() * 1000000)

  // 洗牌
  for (let i = pool.length - 1; i > 0; i--) {
    const j = Math.floor((Math.sin(seed + i) * 10000) % (i + 1))
    ;[pool[i], pool[j]] = [pool[j], pool[i]]
  }

  // 返回中奖者
  return pool.slice(0, winnerCount)
}

// 处理抽奖结果
async function processLotteryResults(allParticipants, winners, product) {
  const db = cloud.database()

  // 处理中奖用户
  for (const winner of winners) {
    await db.collection('orders').doc(winner._id).update({
      data: {
        lotteryStatus: 'win',
        consolationCoupon: 0, // 中奖用户不发安慰奖
        updateTime: new Date()
      }
    })

    // 发送中奖通知（这里简化处理，实际应该使用微信消息订阅）
    console.log(`用户 ${winner.userId} 中奖了！`)
  }

  // 处理未中奖用户
  const losers = allParticipants.filter(p => !winners.includes(p))

  for (const loser of losers) {
    await db.collection('orders').doc(loser._id).update({
      data: {
        lotteryStatus: 'lose',
        lotteryCoupon: product.consolationCoupon || 1000, // 安慰奖，默认10元券
        updateTime: new Date()
      }
    })

    // 给未中奖用户发放安慰奖优惠券
    if (product.consolationCoupon > 0) {
      await grantConsolationCoupon(loser.userId, product.consolationCoupon)
    }
  }
}

// 发放安慰奖优惠券
async function grantConsolationCoupon(userId, couponAmount) {
  const db = cloud.database()

  const couponData = {
    type: 'lotteryConsolation',
    title: '抽奖安慰奖',
    amount: couponAmount,
    minAmount: 5000, // 最低使用金额
    userId: userId,
    status: 0,
    startTime: new Date(),
    endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7天有效期
    createTime: new Date(),
    description: '抽奖未中奖安慰奖，满50元可用',
    categoryLimit: '',
    productLimit: ''
  }

  await db.collection('coupons').add({ data: couponData })
}

// 处理支付回调
const handlePaymentNotify = async (event) => {
  const { orderNo, status } = event

  try {
    const db = cloud.database()

    // 根据订单号查询订单信息
    const orderRes = await db.collection('orders')
      .where({ orderNo: orderNo })
      .limit(1)
      .get()

    if (orderRes.data.length === 0) {
      return {
        success: false,
        message: '订单不存在'
      }
    }

    const order = orderRes.data[0]
    const orderId = order._id

    if (status === 'success') {
      // 支付成功，更新订单状态
      await db.collection('orders').doc(orderId).update({
        data: {
          status: 'paid',
          payTime: new Date(),
          updateTime: new Date()
        }
      })

      // 处理团购逻辑
      if (order.groupType === 'traditional') {
        // 普通团购，检查是否成团
        const groupResult = await handleGroupSuccess({ orderId })
        console.log('普通团购成团检查:', groupResult)
      } else if (order.groupType === 'lottery') {
        // 抽奖团购，检查是否达到开奖条件
        const lotteryResult = await checkLotteryCondition({ orderId })
        console.log('抽奖团购检查:', lotteryResult)
      }

      return {
        success: true,
        message: '支付处理成功'
      }
    } else {
      // 支付失败或取消
      await db.collection('orders').doc(orderId).update({
        data: {
          status: 'cancelled',
          updateTime: new Date()
        }
      })

      // 恢复商品库存
      const productRes = await db.collection('products').doc(order.productId).get()
      const product = productRes.data
      await db.collection('products').doc(order.productId).update({
        data: {
          stock: product.stock + order.quantity,
          updateTime: new Date()
        }
      })

      return {
        success: true,
        message: '订单已取消'
      }
    }

  } catch (error) {
    console.error('处理支付回调失败:', error)
    return {
      success: false,
      message: '处理支付回调失败'
    }
  }
}

// 检查抽奖开奖条件
const checkLotteryCondition = async (event) => {
  const { orderId } = event

  try {
    const db = cloud.database()

    // 获取订单信息
    const orderRes = await db.collection('orders').doc(orderId).get()
    const order = orderRes.data

    // 获取该商品的抽奖活动信息
    const lotteryOrdersRes = await db.collection('orders').where({
      productId: order.productId,
      groupType: 'lottery',
      status: 'paid'
    }).get()

    const totalParticipants = lotteryOrdersRes.data.length;
    const productRes = await db.collection('products').doc(order.productId).get()
    const product = productRes.data

    // 检查是否达到开奖条件
    if (totalParticipants >= product.groupCount) {
      // 达到开奖条件，执行抽奖
      const result = await conductLottery({ groupId: order.productId })

      // 更新所有相关订单的抽奖状态
      await db.collection('orders').where({
        productId: order.productId,
        groupType: 'lottery'
      }).update({
        data: {
          lotteryTime: new Date(),
          updateTime: new Date()
        }
      })

      console.log('执行抽奖成功:', result)
      return {
        success: true,
        message: '已达开奖条件，执行抽奖',
        data: result
      }
    }

    return {
      success: true,
      message: '开奖条件未满足',
      data: {
        current: totalParticipants,
        target: product.groupCount
      }
    }

  } catch (error) {
    console.error('检查开奖条件失败:', error)
    return {
      success: false,
      message: '检查开奖条件失败'
    }
  }
}

// 获取商品列表
const getProducts = async (event) => {
  const { page = 1, pageSize = 20, type = 'all', keyword = '' } = event

  try {
    const db = cloud.database()
    let condition = { status: 1 }

    if (type !== 'all') {
      condition.type = type
    }

    if (keyword) {
      condition.name = db.Command.regExp(keyword, 'i')
    }

    const result = await db.collection('products')
      .where(condition)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy('sort', 'desc')
      .orderBy('createTime', 'desc')
      .get()

    // 获取每个商品的参与人数
    for (let i = 0; i < result.data.length; i++) {
      const product = result.data[i]
      const countRes = await db.collection('orders')
        .where({
          productId: product._id,
          status: _.in(['pending', 'paid'])
        })
        .count()

      product.participants = countRes.total
      product.progressPercent = Math.floor((countRes.total / product.groupCount) * 100)
    }

    return {
      success: true,
      data: result.data,
      message: '商品列表获取成功'
    }

  } catch (error) {
    console.error('获取商品列表失败:', error)
    return {
      success: false,
      message: '获取商品列表失败'
    }
  }
}

// 获取商品详情
const getProductDetail = async (event) => {
  const { productId } = event

  try {
    const db = cloud.database()

    // 获取商品基本信息
    const productRes = await db.collection('products').doc(productId).get()

    if (!productRes.data) {
      return {
        success: false,
        message: '商品不存在'
      }
    }

    const product = productRes.data

    // 获取商品参与情况
    const ordersRes = await db.collection('orders').where({
      productId: productId,
      status: _.in(['pending', 'paid'])
    }).get()

    // 获取用户评价（最新的5条）
    const reviewsRes = await db.collection('reviews').where({
      productId: productId,
      status: 'approved'
    }).limit(5).orderBy('createTime', 'desc').get()

    // 获取相关商品
    const relatedRes = await db.collection('products').where({
      category: product.category,
      _id: _.neq(productId),
      status: 1
    }).limit(4).get()

    const productDetail = {
      ...product,
      participants: ordersRes.data.length,
      currentOrders: ordersRes.data,
      reviews: reviewsRes.data,
      relatedProducts: relatedRes.data
    }

    return {
      success: true,
      data: productDetail,
      message: '商品详情获取成功'
    }

  } catch (error) {
    console.error('获取商品详情失败:', error)
    return {
      success: false,
      message: '获取商品详情失败'
    }
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "updateRecord":
      return await updateRecord(event);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
    case "grantCoupon":
      return await grantCoupon(event);
    case "createGroupOrder":
      return await createGroupOrder(event);
    case "handleGroupSuccess":
      return await handleGroupSuccess(event);
    case "conductLottery":
      return await conductLottery(event);
    case "handlePaymentNotify":
      return await handlePaymentNotify(event);
    case "checkLotteryCondition":
      return await checkLotteryCondition(event);
    case "getProducts":
      return await getProducts(event);
    case "getProductDetail":
      return await getProductDetail(event);
    default:
      return {
        success: false,
        message: "未知操作类型"
      };
  }
};